<template>
  <a-modal :title="title" :width="1200" :after-close="reset" @ok="submit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '120px' } }">
      <a-form-item label="模板名称" name="name">
        <a-input v-model:value="form.name" placeholder="模板名称" />
      </a-form-item>
      <a-form-item label="计费方式" name="type" @change="changeRadio(ruleForm.type)">
        <a-radio-group v-model:value="form.type">
          <a-radio :value="1"> 按件数 </a-radio>
          <a-radio :value="2"> 按重量 </a-radio>
          <a-radio :value="3"> 按体积 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="配送区域及运费" name="region">
        <a-table :dataSource="form.region" :columns="regionCol" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" size="mini" @click="addRegion()">
          <template #icon><edit-outlined /></template>
          添加配送区域
        </a-button>
      </a-form-item>
      <a-form-item label="指定包邮" name="appoint">
        <a-radio-group v-model:value="form.appoint">
          <a-radio :value="true"> 开启 </a-radio>
          <a-radio :value="false"> 关闭 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.appoint === true" name="free">
        <a-table :dataSource="form.free" :columns="feeCol" />
      </a-form-item>
      <a-form-item v-if="form.appoint === true">
        <a-button type="primary" size="mini" @click="addFree()">
          <template #icon><edit-outlined /></template>
          添加指定包邮区域
        </a-button>
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input v-model:value="form.sort" placeholder="排序" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="tsx">
import { cityListTree, shippingFree, shippingRegion, storeAddup, storeinfo } from './api';
import { freightSet, type Ifee, type IfreightSet, type Iregion } from './entity';
import { validReg } from '@/utils/validate';

const props = withDefaults(defineProps<{
  data: Partial<IfreightSet>
}>(), {
})
const title = computed(() => props.data.id ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save })

let baseCol = $ref({
  title: '首件',
  title2: '续件',
  title3: '包邮件数'
})
const kg = '重量（kg）'
const m = '体积（m³）'
const statusMap = [
  {
    title: '首件',
    title2: '续件',
    title3: '包邮件数'
  },
  {
    title: `首件${kg}`,
    title2: `续件${kg}`,
    title3: `包邮${kg}`
  },
  {
    title: `首件${m}`,
    title2: `续件${m}`,
    title3: `包邮${m}`
  }
]
const mulProps = {
  children: 'child',
  label: 'name',
  value: 'cityId',
}
const { tableRef, columns: regionCol } = useTable<Iregion>([
  {
    title: "可配送区域", dataIndex: "name",
    customRender: ({ record, index }) => (
      <>
        {
          index == 0 ? <span >默认全国</span>
            : <a-cascader

              v-model={record.city_ids}
              style="width: 98%"
              options={cityList}
              fieldNames={mulProps}
              collapse-tags
              clearable
              filterable

            />
        }
      </>
    ),
  },
  {
    title: baseCol.title,
    dataIndex: 'first',
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.first} min={form.type === 1 ? 1 : 0.1} />
      </>
    ),
  },
  {
    title: '运费（元）',
    dataIndex: 'firstPrice',
    width: 100,
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.firstPrice} min={0} />
      </>
    ),
  },
  {
    title: baseCol.title2,
    dataIndex: 'renewal',
    width: 100,
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.renewal} min={form.type === 1 ? 1 : 0.1} />
      </>
    ),
  },
  {
    title: '续费（元）',
    dataIndex: 'renewalPrice',
    width: 100,
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.renewalPrice} min={0} />
      </>
    ),
  },
  {
    title: "操作",
    dataIndex: "op",
    customRender: ({ record, index }) => (
      <>
        <confirm-button danger onClick={() => remove(form.region, index)}>
          删除
        </confirm-button>
      </>
    ),
  },
]);
const { tableRef: feeRef, columns: feeCol } = useTable<Ifee>([
  {
    title: "选择地区", dataIndex: "name",
    customRender: ({ record, index }) => (
      <>
        <a-cascader
          v-model={record.city_ids}
          style="width: 98%"
          options={cityList}
          fieldNames={mulProps}
          collapse-tags
          clearable
          filterable
        />
      </>
    ),
  },
  {
    title: baseCol.title3,
    dataIndex: 'number',
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.number} min={0} />
      </>
    ),
  },
  {
    title: '包邮金额（元）',
    dataIndex: 'firstPrice',
    width: 100,
    customRender: ({ record, index }) => (
      <>
        <a-input-number v-model:value={record.price} min={0} />
      </>
    ),
  },
  {
    title: "操作",
    dataIndex: "op",
    customRender: ({ record, index }) => (
      <>
        <confirm-button danger onClick={() => remove(form.free, index)}>
          删除
        </confirm-button>
      </>
    ),
  },
]);
let form = $ref(new freightSet())
let id = $ref<number>()
function changeRadio(num: number) {
  baseCol = Object.assign({}, statusMap[num - 1])
}

function addRegion() {
  form.region.push({
    first: 0,
    firstPrice: 0,
    renewal: 0,
    renewalPrice: 0,
    city_ids: []
  })
}
function addFree() {
  form.free.push({
    city_id: [],
    number: 1,
    price: 1,
    city_ids: []
  })

}
// 不包邮
function queryRegion() {
  shippingRegion({ tempId: id }).then(res => {
    res.forEach((item, index) => {
      item.title = JSON.parse(item.title)
      item.city_ids = item.title
    })
    form.region = res
  })
}
// 包邮
function queryFree() {
  shippingFree({ tempId: id }).then(res => {
    res.forEach((item, index) => {
      item.title = JSON.parse(item.title)
      item.city_ids = item.title
    })
    form.free = res
  })
}
// 列表
function getCityList() {
  cityListTree().then(res => {
    sessionStorage.setItem('cityList', JSON.stringify(res));
    cityList = JSON.parse(sessionStorage.getItem('cityList'));
  }).catch(res => {
    AntMessage.error(res.message)
  })
}
function remove(row: any[], index: number) {
  row.splice(index, 1)
}
watchEffect(() => {
  if (props.data.id) {
    id = props.data.id
    storeinfo(props.data.id).then(res => {
      form.setProps(res)
      // 不包邮地区
      queryRegion()
      // 包邮地区
      if (res.appoint) {
        queryFree()
      }
    })
  }
})

const rules = {
  storeName: [validReg('required', '请输入用户名')]
}
let cityList = $ref([])
onMounted(() => {
  getCityList()
})
const emit = defineEmits(['change'])
function save() {
  let { region, free, appoint, ...temp } = form
  let shippingTemplatesFreeRequestList = []
  let shippingTemplatesRegionRequestList = region.map(el => {
    el.title = el.city_ids.length > 0 ? JSON.stringify(el.city_ids) : JSON.stringify([[0, 0]])
    for (var i = 0;i < el.city_ids.length;i++) {
      el.city_ids[i].shift()
    }
    el.cityId = el.city_ids.length > 0 ? el.city_ids.join(',') : 'all'
  })
  if (appoint) {
    shippingTemplatesFreeRequestList = free.map(el => {
      el.title = el.city_ids.length > 0 ? JSON.stringify(el.city_ids) : JSON.stringify([[0, 0]])
      for (var i = 0;i < el.city_ids.length;i++) {
        el.city_ids[i].shift()
      }
      el.cityId = el.city_ids.length > 0 ? el.city_ids.join(',') : 'all'
    })
  }
  storeAddup({ ...temp, appoint, shippingTemplatesRegionRequestList, shippingTemplatesFreeRequestList }).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}

function reset() {
  form = new freightSet()
}
</script>

<style lang="less"></style>
